/* eslint-disable */
/**
 * Created by admin on 2018/12/17.
 */
function prevHeight(type = 1) {
    if (type === 1) {
        document.querySelector('body').style.height = '100%'
        document.querySelector('html').style.height = '100%'
        document.querySelector('#app').style.height = '100%'
    } else {
        document.querySelector('body').style.height = ''
        document.querySelector('html').style.height = ''
        document.querySelector('#app').style.height = ''
    }
}

function deepAssign(to, from) {
    for (let key in from) {
        if (!to[key] || typeof to[key] !== 'object') {
            to[key] = from[key]
        } else {
            deepAssign(to[key], from[key])
        }
    }
}

function createAddAPI(baseObj) {
    return function add(...args) {
        if (typeof args[0] === 'string') {
            args[0] = {
                [args[0]]: args[1]
            }
        }
        deepAssign(baseObj, args[0])
    }
}

function judgeTypeFnCreator(type) {
    const toString = Object.prototype.toString
    return function isType(o) {
        return toString.call(o) === `[object ${type}]`
    }
}
const camelizeRE = /-(\w)/g

function camelize(str) {
    str = String(str)
    return str.replace(camelizeRE, function(m, c) {
        return c ? c.toUpperCase() : ''
    })
}

function kebab(str) {
    str = String(str)
    return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}
const typesReset = {
    _set(obj, key, value) {
        obj[key] = value
    },
    string(obj, key) {
        typesReset._set(obj, key, '')
    },
    number(obj, key) {
        typesReset._set(obj, key, 0)
    },
    boolean(obj, key) {
        typesReset._set(obj, key, false)
    },
    object(obj, key, value) {
        if (Array.isArray(value)) {
            typesReset._set(obj, key, [])
        } else {
            typesReset._set(obj, key, {})
        }
    }
}

function resetTypeValue(obj, key, defVal) {
    if (defVal !== undefined) {
        return typesReset._set(obj, key, defVal)
    }
    if (key) {
        const value = obj[key]
        const resetHandler = typesReset[typeof value]
        resetHandler && resetHandler(obj, key, value)
    } else {
        Object.keys(obj).forEach((key) => {
            resetTypeValue(obj, key)
        })
    }
}

function parallel(tasks, cb) {
    let doneCount = 0
    let results = []
    const tasksLen = tasks.length
    if (!tasksLen) {
        return cb(results)
    }
    tasks.forEach((task, i) => {
        task((ret) => {
            doneCount += 1
            results[i] = ret
            if (doneCount === tasksLen) {
                // all tasks done
                cb(results)
            }
        })
    })
}

function cb2PromiseWithResolve(cb) {
    let promise
    if (typeof window.Promise !== 'undefined') {
        const _cb = cb
        promise = new window.Promise((resolve) => {
            cb = (data) => {
                _cb && _cb(data)
                resolve(data)
            }
        })
        promise.resolve = cb
    }
    return promise
}

function debounce(func, wait, immediate, initValue) {
    let timeout
    let result = initValue

    const later = function(context, args) {
        timeout = null
        if (args) {
            result = func.apply(context, args)
        }
    }

    const debounced = function(...args) {
        if (timeout) {
            clearTimeout(timeout)
        }
        if (immediate) {
            const callNow = !timeout
            timeout = setTimeout(later, wait)
            if (callNow) {
                result = func.apply(this, args)
            }
        } else {
            timeout = setTimeout(() => {
                later(this, args)
            }, wait)
        }

        return result
    }

    debounced.cancel = function() {
        clearTimeout(timeout)
        timeout = null
    }

    return debounced
}

function processComponentName(Component, { prefix = '', firstUpperCase = false } = {}) {
    const name = Component.name
    const pureName = name.replace(/^cube-/i, '')
    let camelizeName = `${camelize(`${prefix}${pureName}`)}`
    /* istanbul ignore if */
    if (firstUpperCase) {
        camelizeName = camelizeName.charAt(0).toUpperCase() + camelizeName.slice(1)
    }
    return camelizeName
}

function parsePath (obj, path = '') {
    const segments = path.split('.')
    let result = obj
    for (let i = 0; i < segments.length; i++) {
        const key = segments[i]
        /* istanbul ignore if */
        if (isUndef(result[key])) {
            result = ''
            break
        } else {
            result = result[key]
        }
    }
    return result
}

const isFunc = judgeTypeFnCreator('Function')
const isUndef = judgeTypeFnCreator('Undefined')
const isArray = judgeTypeFnCreator('Array')
const isString = judgeTypeFnCreator('String')
const isObject = judgeTypeFnCreator('Object')
const isNumber = judgeTypeFnCreator('Number')
const findIndex = function(ary, fn) {
    if (ary.findIndex) {
        return ary.findIndex(fn)
    }
    /* istanbul ignore next */
    let index = -1
    /* istanbul ignore next */
    ary.some(function (item, i, ary) {
        const ret = fn.call(this, item, i, ary)
        if (ret) {
            index = i
            return ret
        }
    })
    /* istanbul ignore next */
    return index
}

const mathChoose = function(arr, size) {
    var allResult = [];
    let func = function (arr, size, result) {
        var arrLen = arr.length;
        if (size > arrLen) {
            return;
        }
        if (size == arrLen) {
            allResult.push([].concat(result, arr))
        } else {
            for (var i = 0 ; i < arrLen; i++) {
                var newResult = [].concat(result);
                newResult.push(arr[i]);

                if (size == 1) {
                    allResult.push(newResult);
                } else {
                    var newArr = [].concat(arr);
                    newArr.splice(0, i + 1);
                    func(newArr, size - 1, newResult);
                }
            }
        }
    };
    func(arr, size,[]);
    return allResult;
};

/*彩票方法 根据玩法名称写的方法*/
const lhc_lxlw =  function (tag_content, arr) {
    let odds;
    let i = arr.indexOf('狗');
    if (i >= 0){
        return tag_content['狗'];
    } else {
        return tag_content[arr[0]];
    }
}

const lhc_lm_odds= function (tag_content, play) {
    let odds = '';
    switch (play) {
        case 'lhc_sanzhonger':
            odds = tag_content['sz2'];
            break;
        case 'lhc_sanquanzhong':
            odds = tag_content['sqz'];
            break;
        case 'lhc_erquanzhong':
            odds = tag_content['eqz'];
            break;
        case 'lhc_erzhongte':
            odds = tag_content['ezt'];
            break;
        case 'lhc_techuan':
            odds = tag_content['tc'];
            break;
        case 'lhc_siquanzhong':
            odds = tag_content['siqz'];
            break;
    }

    return odds;
}

const hasOwn = (obj, type) => {
    return Object.prototype.hasOwnProperty.call(obj, type);
}

const isEmpty = (item) => {
    item = getString(item);
    if ("" == strim(item))
        return true;
    return false;
}

const isUndefined = item => {
    return typeof item === 'undefined';
}

const isDefined = item => {
    return !isUndefined(item);
}

const getString = (item, defaultStr) => {
    if (isString(item)) return item.trim();
    if (isNumber(item)) return `${item}`.trim();
    return defaultStr || '';
}
const getNumber = (item, defaultNum) => {
    var matches = getString(item).match(/\d+/);
    return isNumber(matches && +matches[0]) ? +matches[0] : defaultNum;
}
const getArray = (item, defaultArr) => {
    item = strToObject(item);
    return isArray(item) ? item : (defaultArr || []);
}
const getObject = (item, defaultObj) => {
    item = strToObject(item);
    return item ? item : (defaultObj || {});
}
const getFunction = (item) => {
    return isFunction(item) ? item : noop;
}

const isEqual = (x, y) => {
    if (x === y) {
        return true;
    }

    if (!(x instanceof Object) || !(y instanceof Object)) {
        return false;
    }

    if (x.constructor !== y.constructor) {
        return false;
    }

    for (var p in x) {
        if (x.hasOwnProperty(p)) {
            if (!y.hasOwnProperty(p)) {
                return false;
            }
            if (x[p] === y[p]) {
                continue;
            }
            if (typeof (x[p]) !== "object") {
                return false;
            }
            if (!Object.equals(x[p], y[p])) {
                return false;
            }
        }
    }

    for (p in y) {
        if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
            return false;
        }
    }
    return true;
}

const json = item => {
    let str = {
        type: Object.prototype.toString.call(item)
    }
    try {
        str = JSON.stringify(item)
    } catch (e) {
        str.error = e && e.stack || ''
    }
    return isString(str) ? str : $json(str)
}
const parse = item => {
    let obj = {
        type: Object.prototype.toString.call(item)
    }
    try {
        obj = JSON.parse(item)
    } catch (e) {
        obj.error = e && e.stack || ''
    }
    return isObject(obj) ? obj : $parse(obj)
}

const isPhone = (str) => {
    return /^1\d{10}$/.test(str)
}

const isEmail = (str) => {
    return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str)
}

const strToObject = (str) => {
    var res = undefined;
    if (isObject(str))
        return str;
    try {
        res = JSON.parse(str);
    } catch (e) {

    }
    if (!res instanceof Object) {
        res = undefined;
    }
    return res;
}

const trim = function (str) {
    return str.replace(/(^\s*)|(\s*$)/g, '');
}
//删除左边的空格
const ltrim = function (str) {
    return str.replace(/(^\s*)/g, '');
}
//删除右边的空格
const rtrim = function (str) {
    return str.replace(/(\s*$)/g, '');
}
//去除所有空格
const strim = function (str) {
    return str.replace(/\s/g, '');
}

const isWechat = () => {
    let ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == 'micromessenger';
}

const getQuery = name => {
    var reg = new RegExp(".*(^|\\#|\\?|\\&)"+name+"=([^\\&|\\#]*)(\\&|$)", 'i');
    var r = document.URL.match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

const hasClass = (elem, cls) => {
    cls = cls || '';
    if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时，返回false
    return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
}
   
const addClass =(ele, cls) => {
    if (!hasClass(ele, cls)) {
        ele.className = ele.className == '' ? cls : ele.className + ' ' + cls;
    }
}
   
const removeClass = (elem, cls) => {
    if (hasClass(elem, cls)) {
        var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' ';
        while (newClass.indexOf(' ' + cls + ' ') >= 0) {
            newClass = newClass.replace(' ' + cls + ' ', ' ');
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    }
}

//判断对象个数
const attributeCount = function(obj) {
    let count = 0;
    for(let i in obj) {
        if(obj.hasOwnProperty(i)) {  // 建议加上判断,如果没有扩展对象属性可以不加
            count++;
        }
    }
    return count;
};


// 时间格式化
const timeformat = function (str, format, tissue) {
    var myDate = new Date();
    str = (str == 0 || !str || str == 'undefined' || str == NaN) ? myDate.getTime() : str;
    str = (typeof str == 'string') ? str.replace(/\-/g, '/') : str;
    (!format || format == '') ? format = 'y-m-d h:i:s': format;
    var nowstamp = parseInt(myDate.getTime() / 1000),
        itemtime = parseInt(str),
        year, m, d, h, i, s;
    if (format == 'timestamp') {
        (str === +str) ? str = parseInt(str): str = Date.parse(str);
        if (str > 100000000000) {
            str = str / 1000;
        }
        return str;
    }
    if (itemtime < 10000) {
        //普通时间直接转换
        itemtime = Date.parse(str);
    }
    if (itemtime > 100000000000) {
        itemtime = itemtime / 1000;
    }
    var timebe = nowstamp - itemtime;
    if (tissue && tissue > -1 && tissue < 864000 && timebe < tissue) {
        if (timebe > 86400) {
            //超过1天，按天计算
            return Math.floor(timebe / 86400) + '天前';
        } else if (timebe > 3600) {
            //超过1小时，按小时计算
            return Math.floor(timebe / 3600) + '小时前';
        } else if (timebe > 59) {
            //按分钟计算
            return Math.ceil(timebe / 60) + '分钟前';
        } else {
            return '刚刚';
        }
    } else {
        itemtime = myDate.setTime(itemtime * 1000);
        year = myDate.getFullYear();
        m = (myDate.getMonth() + 1 < 10) ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1;
        d = (myDate.getDate() < 10) ? '0' + (myDate.getDate()) : myDate.getDate();
        h = (myDate.getHours() < 10) ? '0' + (myDate.getHours()) : myDate.getHours();
        i = (myDate.getMinutes() < 10) ? '0' + (myDate.getMinutes()) : myDate.getMinutes();
        s = (myDate.getSeconds() < 10) ? '0' + (myDate.getSeconds()) : myDate.getSeconds();

        if ("object" == format.toLowerCase()) {
            return {
                year: year,
                mon: m,
                day: d,
                hour: h,
                min: i,
                sec: s
            };
        }

        return format.replace('y', year).replace('m', m).replace('d', d).replace('h', h).replace('i', i).replace('s', s);
    }
}

const compress = function (fileObj, dom) {
    let reader = new FileReader()
    reader.readAsDataURL(fileObj)
    reader.onload = function(e) {
        let image = new Image() //新建一个img标签（还没嵌入DOM节点)
        image.src = e.target.result
        image.onload = function() {
            let canvas = document.createElement('canvas'),
                context = canvas.getContext('2d'),
                imageWidth = image.width / 2,    //压缩后图片的大小
                imageHeight = image.height / 2,
                data = ''

            canvas.width = imageWidth
            canvas.height = imageHeight

            context.drawImage(image, 0, 0, imageWidth, imageHeight)
            data = canvas.toDataURL('image/jpeg');

            let origin = dom.getAttribute('data-src');
            let newsrc = '';
            if (!origin) {
                newsrc = data;
            } else {
                newsrc = origin + ',,,,' + data;
            }
            let html = '<img src=" '+data+'" style="height: 53px;width:53px;margin-left: 6px;"/>'
            let originhtml = document.getElementById('showimg').innerHTML;
            document.getElementById('showimg').innerHTML = originhtml + html;
            dom.setAttribute('data-src', newsrc);
        }
    }
}

export {
    attributeCount,
    findIndex,
    deepAssign,
    createAddAPI,
    resetTypeValue,
    parallel,
    cb2PromiseWithResolve,
    debounce,
    processComponentName,
    parsePath,
    camelize,
    kebab,
    prevHeight,
    isUndef,
    isFunc,
    isArray,
    isString,
    isObject,
    isNumber,
    mathChoose,
    lhc_lxlw,
    lhc_lm_odds,
    isWechat,
    getQuery,
    hasClass,
    addClass,
    removeClass,
    hasOwn,
    isEmpty,
    isDefined,
    isEmail,
    isPhone,
    getArray,
    getFunction,
    getNumber,
    getObject,
    getString,
    trim,
    ltrim,
    rtrim,
    strim,
    strToObject,
    timeformat,
    compress
};
export default {
    attributeCount,
    findIndex,
    deepAssign,
    createAddAPI,
    resetTypeValue,
    parallel,
    cb2PromiseWithResolve,
    debounce,
    processComponentName,
    parsePath,
    camelize,
    kebab,
    prevHeight,
    isUndef,
    isFunc,
    isArray,
    isString,
    isObject,
    isNumber,
    mathChoose,
    lhc_lxlw,
    lhc_lm_odds,
    isWechat,
    getQuery,
    hasClass,
    addClass,
    removeClass,
    hasOwn,
    isEmpty,
    isDefined,
    isEmail,
    isPhone,
    getArray,
    getFunction,
    getNumber,
    getObject,
    getString,
    trim,
    ltrim,
    rtrim,
    strim,
    strToObject,
    timeformat,
    compress
}